const { validate, validations } = require('ws-chat-common').validate
const { userSocketCollection, webSocketMessageActions } =
  require('ws-chat-common').constants
const db = uniCloud.database()
const userdb = db.collection('sys_user')
const ws = uniCloud.webSocketServer()

function checkUser(id) {
  return new Promise((resolve, reject) => {
    userdb
      .doc(id)
      .get()
      .then(async (res) => {
        if (res.data.length == 0) {
          await ws.send(connectionId, {
            code: 400,
            data: null,
            message: '异常账户',
          })
          resolve(false)
        } else {
          resolve(res.data[0])
        }
      })
  })
}

module.exports = async function connection(event) {
  const { connectionId } = event
  const query = validate(validations.websocket.connection, event.query)
  const data = await checkUser(query.userId)
  if (!data) return
  await ws.send(connectionId, {
    code: 88,
    data: null,
    message: '连接成功',
  })
  await userSocketCollection.add({
    userId: query.userId,
    type: data.type,
    onLine: 1,
    connectionId,
    connectedAt: Date.now(),
  })
}
